import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: window.localStorage.getItem('userinfo')?.userName || '管理员',
  avatar: window.localStorage.getItem('userinfo')?.avatarUrl || '',
  introduction: '',
  roles: [],
  userId: getUserId(),
  zcrouter: [], //  菜单
  zcbtn: {} // 按钮
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_ZCROUTER: (state, zcrouter) => {
    state.zcrouter = zcrouter
  },
  SET_ZCBTN: (state, zcbtn) => {
    state.zcbtn = zcbtn
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password }).then(data => {
        // console.log(data);
        /**
               * {
               *     "avatarUrl": "https://menjian.cjzxkj.com/static/Wmdk-0ZqNP-GVMai7xUSm.png",
               *     "userName": "admin",
               *     "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjQsImV4cCI6MTcyMzIwNjQ0MH0.BO2bG0rWGf7daFBGS_DdvHXFwEvK0j6RxcER_hbMa6o"
               * }
               */
        window.localStorage.setItem('userinfo', JSON.stringify(data))
        // 登录返回的数据
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户详情
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // console.log('获取兴趣', state.userId)
      getInfo(state.token, state.userId).then(data => {
        // console.log(state.userId)
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const roles = ['admin']
        // 路由 姓名  头像
        const { username, avatar, role_data } = data

        const arrx = {} // 按钮权限

        // 权限清洗函数
        function zc(item) {
          if (item.length !== 0) {
            item.forEach((e, i) => {
              if (e.type == 3) {
                arrx[e.sign] = e.hidden == 0
                if (item.length - 1 == i) {
                  item = item.length = 0
                }
              } else {
                zc(e.children)
              }
            })
          }
        }

        function zc2(item) {
          if (item.length !== 0) {
            item.forEach((e, i) => {
              if (e.type == 3) {
                item = item.length = 0
              } else {
                zc2(e.children)
              }
            })
          }
        }

        // 菜单权限
        const obj = JSON.parse(JSON.stringify(role_data))
        const obj2 = JSON.parse(JSON.stringify(role_data))
        zc(obj)
        commit('SET_ZCBTN', arrx)
        // console.log('按钮权限', arrx)
        zc2(obj2)
        commit('SET_ZCROUTER', obj2)

        commit('SET_ROLES', roles)
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)

        resolve({ roles })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // // user logout
  // logout({ commit, state, dispatch }) {
  //     return new Promise((resolve, reject) => {
  //         logout(state.token).then(() => {
  //             commit('SET_TOKEN', '')
  //             commit('SET_ROLES', [])

  //             removeToken()
  //             resetRouter()

  //             // reset visited views and cached views
  //             // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //             dispatch('tagsView/delAllViews', null, { root: true })

  //             resolve()
  //         }).catch(error => {
  //             reject(error)
  //         })
  //     })
  // },

  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_NAME', '')
      commit('SET_ZCROUTER', {})
      commit('SET_TOKEN', '')
      commit('SET_USER_ID', '')
      commit('SET_ROLES', [])
      commit('SET_AVATAR', '')
      removeToken()
      removeUserId()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
